import { Layout, Menu } from 'antd'
import { useEffect, useState } from 'react'
import style from './index.module.scss'
import './index.scss'
import { useLocation, useNavigate } from 'react-router-dom'
import { type MenuItem } from '@/store/modules/menu/type'
import { convertIconsToComponents, useMenuList } from '@/hooks/useMenu'
const { Sider } = Layout

export default function Aside() {
  // 控制菜单的折叠展开
  const [collapsed, setCollapsed] = useState<boolean>(false)
  // 路由路径
  const { pathname } = useLocation()
  // 路由跳转
  const navigateTo = useNavigate()

  // 菜单列表
  const [items] = useState<MenuItem[]>(convertIconsToComponents(useMenuList()))

  // 切换菜单回调
  const changeMenu = (e: { key: string }) => {
    navigateTo(e.key)
  }

  // 菜单展开的数组
  const [openKeys, setOpenKeys] = useState<string[]>([])

  // 子菜单展开/关闭回调
  const onOpenChange = (keys: string[]) => {
    setOpenKeys([keys[keys.length - 1]])
  }

  // 菜单展开/关闭
  useEffect(() => {
    let groupTitles = document.querySelectorAll('.ant-menu-item-group-title')
    groupTitles.forEach((item) => {
      if (collapsed) {
        item.className = 'ant-menu-item-group-title hidden'
      } else {
        item.className = 'ant-menu-item-group-title'
      }
    })
  }, [collapsed])

  const [selectedKeys, setSelectedKeys] = useState<string[]>([pathname])

  useEffect(() => {
    setSelectedKeys([pathname])
  }, [pathname])

  return (
    <>
      <Sider
        collapsible
        theme='light'
        collapsed={collapsed}
        onCollapse={(value) => setCollapsed(value)}
        className={style.siderContent}
      >
        {/* logo */}
        <div className={style['demo-logo-vertical']}>
          <img
            src='/images/logo.png'
            alt=''
          />
          {!collapsed ? <h1>歪fChat后台管理系统</h1> : <></>}
        </div>
        {/* 菜单列表 */}
        <Menu
          defaultSelectedKeys={[pathname]}
          defaultOpenKeys={openKeys}
          selectedKeys={selectedKeys}
          openKeys={openKeys}
          mode='inline'
          items={items}
          onClick={changeMenu}
          onOpenChange={onOpenChange}
        />
      </Sider>
    </>
  )
}
